package com.JWH_TV.utils

import com.JWH_TV.domain.Sample

public class SlidingPercentile(private val maxWeight: Int = 2000) {
    private val samples = mutableListOf<Sample>()
    private var totalWeight = 0

    // 添加采样点
    fun addSample(sample: Sample) {
        // 加入新的采样点
        samples.add(sample)
        totalWeight += sample.weight

        // 如果总权重大于最大权重值，则移除最先加入的采样点
        while (totalWeight > maxWeight && samples.isNotEmpty()) {
            val removed = samples.removeAt(0)
            totalWeight -= removed.weight
        }
    }

    // 获取网速估计值
    fun getEstimatedBandwidth(): Float {
        // 排序采样点按值（value）从小到大
        val sortedSamples = samples.sortedBy { it.value }

        val desiredWeight = totalWeight / 2
        var accumulatedWeight = 0
        for (sample in sortedSamples) {
            accumulatedWeight += sample.weight
            if (accumulatedWeight >= desiredWeight) {
                return sample.value
            }
        }
        return sortedSamples.last().value // 如果累积的权重不足以达到 desiredWeight，返回最后一个采样点的值
    }
}